﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using NetworkInterfaceUtility;

namespace CluelessGame
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private GameManager gameManager;
        private Dictionary<Weapon, BitmapImage> weaponImageMap = new Dictionary<Weapon, BitmapImage>();
        private Dictionary<Character, BitmapImage> characterImageMap = new Dictionary<Character, BitmapImage>();
        private Dictionary<BitmapImage, Card> handImageMap = new Dictionary<BitmapImage, Card>();

        CharacterSelectionScreen characterSelectionScreen = null;

        NotebookScreen noteBookScreen = new NotebookScreen();

        public bool HostNewGameEnabled
        {
            get { return !(App.NIU.Hosting || App.NIU.ConnectedToHost); }
        }

        public bool JoinNewGameEnabled
        {
            get { return !(App.NIU.Hosting || App.NIU.ConnectedToHost); }
        }

        public bool DisconnectEnabled
        {
            get { return (App.NIU.Hosting || App.NIU.ConnectedToHost); }
        }

        public bool StartGameEnabled
        {
            get { return App.NIU.Hosting; }
        }

        public GameManager CurrentGameManager
        {
            get { return gameManager; }
            set { gameManager = value; NotifyPropertyChanged("CurrentGameManager"); }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }  
        
        #endregion


        public List<BitmapImage> CardsInHand
        {
            get { return handImageMap.Keys.ToList(); }
        }

        public MainWindow()
        {
            InitializeComponent();

            messageTextBox.Focus();
        }

        private void sendClick(object sender, RoutedEventArgs e)
        {
            if (messageTextBox.Text.Length == 0)
                return;

            string messageText = CurrentGameManager.LocalPlayer.Name + ": " + messageTextBox.Text;
            chatTextBox.AppendText( messageText + Environment.NewLine);
            chatTextBox.ScrollToEnd();
            App.NIU.BroadcastNetworkMessage(new ChatMessage((int)NIUMessageIDs.CHAT_MESSAGE, messageText));
            messageTextBox.Text = "";
        }

        protected void HandleStartGameNetworkMessage(NetworkMessageData message)
        {
            StartGameMessage startGameMessage = message as StartGameMessage;

            characterSelectionScreen.ForceClose();
            CurrentGameManager.StartGame(startGameMessage.playerTurn);
        }

        protected void HandleChatMessageNetworkMessage(NetworkMessageData message)
        {
            ChatMessage chatMessage = message as ChatMessage;
            if (chatMessage == null)
            {
                return;
            }

            chatTextBox.AppendText(chatMessage.text + Environment.NewLine);
            chatTextBox.ScrollToEnd();
        }

        protected void HandleBeginSelectCharactersNetworkMessage(NetworkMessageData message)
        {
            characterSelectionScreen = new CharacterSelectionScreen(CurrentGameManager);
            characterSelectionScreen.Show();
        }

        protected void HandleDisproveSuggestionNetworkMessage(NetworkMessageData message)
        {
            DisproveSuggestionMessage disproveSuggestionMessage = message as DisproveSuggestionMessage;

            if (CurrentGameManager.Suggesting)
            {
                CurrentGameManager.Suggesting = false;

                BitmapImage image = GetBitmapImageFromCard(disproveSuggestionMessage.disproveCard);

                ImagePopup imagePopup = new ImagePopup(image, String.Format("{0} shows you:", CurrentGameManager.Players[disproveSuggestionMessage.SourceClientID + 1]));
                imagePopup.ShowDialog();
            }
            else
            {
                MessageBox.Show(String.Format("{0} shows the suggester a card.", CurrentGameManager.Players[disproveSuggestionMessage.SourceClientID + 1]));
            }
        }


        private void buttonNotebook_Click(object sender, RoutedEventArgs e)
        {
            noteBookScreen.Show();
        }

        private void hostNewGameClick(object sender, RoutedEventArgs e)
        {
            App.NIU.Host(5);
            CurrentGameManager.Players[0].InGame = true;

            NotifyPropertyChanged("HostNewGameEnabled");
            NotifyPropertyChanged("JoinNewGameEnabled");
            NotifyPropertyChanged("DisconnectEnabled");
            NotifyPropertyChanged("StartGameEnabled");
        }

        private void joinNewGameClick(object sender, RoutedEventArgs e)
        {
            try
            {
                App.NIU.Connect(JoinGameScreen.GetIP());
            }
            catch (Exception exception)
            {
                MessageBox.Show("Unhandled exception occured while trying to connect: " + exception.Message);
            }

            NotifyPropertyChanged("HostNewGameEnabled");
            NotifyPropertyChanged("JoinNewGameEnabled");
            NotifyPropertyChanged("DisconnectEnabled");
            NotifyPropertyChanged("StartGameEnabled");
        }

        private void startGameClick(object sender, RoutedEventArgs e)
        {
            OnGameObjectsChanged(GameManager.CurrentGameObjects);

            foreach (Player player in CurrentGameManager.Players)
            {
                player.AssociatedCharacter = null;
            }

            App.NIU.BroadcastNetworkMessage(new BeginSelectCharactersMessage((int)NIUMessageIDs.BEGIN_SELECT_CHARACTERS));

            characterSelectionScreen = new CharacterSelectionScreen(CurrentGameManager);
            characterSelectionScreen.Show();

            NotifyPropertyChanged("HostNewGameEnabled");
            NotifyPropertyChanged("JoinNewGameEnabled");
            NotifyPropertyChanged("DisconnectEnabled");
            NotifyPropertyChanged("StartGameEnabled");
        }

        private void saveClick(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.ShowDialog();
        }

        private void loadClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
        }

        private void buttonAccuse_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentGameManager.IsLocalPlayerTurn)
            {
                AccusationScreen accusationScreen = new AccusationScreen();
                accusationScreen.ShowDialog();

                if (accusationScreen.OK)
                {
                    CrimeCards selectedCrimeCards = new CrimeCards();
                    selectedCrimeCards.Character = accusationScreen.SelectedCharacter.AssociatedCard;
                    selectedCrimeCards.Room = accusationScreen.SelectedRoom.AssociatedCard;
                    selectedCrimeCards.Weapon = accusationScreen.SelectedWeapon.AssociatedCard;

                    App.NIU.BroadcastNetworkMessage(new MakeAccusationMessage((int)NIUMessageIDs.MAKE_ACCUSATION,
                        selectedCrimeCards));

                    if (CurrentGameManager.Accusation(CurrentGameManager.LocalPlayer, selectedCrimeCards))
                    {
                        string message = "Your accusation was correct! You win!";
                        App.ErrorLog.LogError(message);
                        MessageBox.Show(message);
                    }
                    else
                    {
                        string message = String.Format("Your accusation was incorrect! You lose! The correct information was {0} with the {1} in the {2}.",
                            GameManager.CurrentGameObjects.CurrentCrimeCards.Character,
                            GameManager.CurrentGameObjects.CurrentCrimeCards.Weapon,
                            GameManager.CurrentGameObjects.CurrentCrimeCards.Room);
                        App.ErrorLog.LogError(message);
                        MessageBox.Show(message);
                        CurrentGameManager.EndTurn();
                    }
                }
            }
        }

        private void changeNameClick(object sender, RoutedEventArgs e)
        {
            string newName = ChangeNameScreen.GetName();

            if (!String.IsNullOrEmpty(newName))
            {
                CurrentGameManager.LocalPlayer.Name = newName;
                App.NIU.BroadcastNetworkMessage(new PlayerNameChangeMessage((Int32)NIUMessageIDs.PLAYER_NAME_CHANGE, newName));
            }
        }

        private void gameBoardImage_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Point location = e.GetPosition(sender as UIElement);

            if (CurrentGameManager.IsLocalPlayerTurn)
            {

            }
        }

        private void Card_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Image image = sender as Image;
            if (image == null)
            {
                MessageBox.Show("Unexpected error occured: could not determine clicked card");
                return;
            }
            BitmapImage bitmapImage = image.Source as BitmapImage;
            if (bitmapImage == null)
            {
                MessageBox.Show("Unexpected error occured: could not determine clicked card");
                return;
            }
            if (!handImageMap.ContainsKey(bitmapImage))
            {
                MessageBox.Show("Unexpected error occured: could not determine clicked card");
                return;
            }

            if (CurrentGameManager.Disproving)
            {
                if (CurrentGameManager.BeginDisprove(handImageMap[bitmapImage]))
                {
                    ImagePopup imagePopup = new ImagePopup(bitmapImage, String.Format("You show the suggester:"));
                    imagePopup.ShowDialog();
                }
            }
            UpdateCards(GameManager.CurrentGameObjects.Hands[CurrentGameManager.LocalPlayer]);
        }

        private void OnGameObjectsChanged(GameObjects gameObjects)
        {
            if (gameObjects.Hands != null)
            {
                if (gameObjects.Hands[CurrentGameManager.LocalPlayer] != null)
                {
                    UpdateCards(gameObjects.Hands[CurrentGameManager.LocalPlayer]);
                }
            }

            CurrentGameBoard.Ballroom.Children.Clear();
            CurrentGameBoard.Hall.Children.Clear();
            CurrentGameBoard.Diningroom.Children.Clear();
            CurrentGameBoard.Study.Children.Clear();
            CurrentGameBoard.Lounge.Children.Clear();
            CurrentGameBoard.Library.Children.Clear();
            CurrentGameBoard.Billiardroom.Children.Clear();
            CurrentGameBoard.Conservatory.Children.Clear();
            CurrentGameBoard.Kitchen.Children.Clear();

            CurrentGameBoard.HallwayBallroomKitchen.Children.Clear();
            CurrentGameBoard.HallwayBilliardroomBallroom.Children.Clear();
            CurrentGameBoard.HallwayBilliardroomDiningroom.Children.Clear();
            CurrentGameBoard.HallwayConservatorBallroom.Children.Clear();
            CurrentGameBoard.HallwayDiningroomKitchen.Children.Clear();
            CurrentGameBoard.HallwayHallBilliardroom.Children.Clear();
            CurrentGameBoard.HallwayHallLounge.Children.Clear();
            CurrentGameBoard.HallwayLibraryBilliardroom.Children.Clear();
            CurrentGameBoard.HallwayLibraryConservatory.Children.Clear();
            CurrentGameBoard.HallwayLoungeDiningroom.Children.Clear();
            CurrentGameBoard.HallwayStudHall.Children.Clear();
            CurrentGameBoard.HallwayStudyLibrary.Children.Clear();

            UpdateCharacters(gameObjects);
            UpdateWeapons(gameObjects);
        }

        private void UpdateWeapons(GameObjects gameObjects)
        {
            weaponImageMap = new Dictionary<Weapon, BitmapImage>();

            weaponImageMap.Add(gameObjects.Candlestick, new BitmapImage(new System.Uri("/CluelessGame;component/Images/CandleStick.png", UriKind.RelativeOrAbsolute)));
            weaponImageMap.Add(gameObjects.Knife, new BitmapImage(new System.Uri("/CluelessGame;component/Images/Knife.png", UriKind.RelativeOrAbsolute)));
            weaponImageMap.Add(gameObjects.Pipe, new BitmapImage(new System.Uri("/CluelessGame;component/Images/Pipe.png", UriKind.RelativeOrAbsolute)));
            weaponImageMap.Add(gameObjects.Revolver, new BitmapImage(new System.Uri("/CluelessGame;component/Images/Revolver.png", UriKind.RelativeOrAbsolute)));
            weaponImageMap.Add(gameObjects.Rope, new BitmapImage(new System.Uri("/CluelessGame;component/Images/Rope.png", UriKind.RelativeOrAbsolute)));
            weaponImageMap.Add(gameObjects.Wrench, new BitmapImage(new System.Uri("/CluelessGame;component/Images/Wrench.png", UriKind.RelativeOrAbsolute)));

            Image image = new Image { Source = weaponImageMap[gameObjects.Candlestick], Width = 50, Height = 80, RenderTransformOrigin = new Point(0.5,0.5)};
            UpdateIcon(gameObjects, gameObjects.Candlestick, image);
            image = new Image { Source = weaponImageMap[gameObjects.Knife], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.Knife, image);
            image = new Image { Source = weaponImageMap[gameObjects.Pipe], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.Pipe, image);
            image = new Image { Source = weaponImageMap[gameObjects.Revolver], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.Revolver, image);
            image = new Image { Source = weaponImageMap[gameObjects.Rope], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.Rope, image);
            image = new Image { Source = weaponImageMap[gameObjects.Wrench], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.Wrench, image);
        }

        private void UpdateCharacters(GameObjects gameObjects)
        {
            characterImageMap = new Dictionary<Character, BitmapImage>();

            characterImageMap.Add(gameObjects.ColonelMustard, new BitmapImage(new System.Uri("/CluelessGame;component/Images/ColonelMustard.png", UriKind.RelativeOrAbsolute)));
            characterImageMap.Add(gameObjects.MissScarlet, new BitmapImage(new System.Uri("/CluelessGame;component/Images/MissScarlet.png", UriKind.RelativeOrAbsolute)));
            characterImageMap.Add(gameObjects.MrGreen, new BitmapImage(new System.Uri("/CluelessGame;component/Images/MrGreen.png", UriKind.RelativeOrAbsolute)));
            characterImageMap.Add(gameObjects.MsPeakcock, new BitmapImage(new System.Uri("/CluelessGame;component/Images/MsPeacock.png", UriKind.RelativeOrAbsolute)));
            characterImageMap.Add(gameObjects.MsWhite, new BitmapImage(new System.Uri("/CluelessGame;component/Images/MsWhite.png", UriKind.RelativeOrAbsolute)));
            characterImageMap.Add( gameObjects.ProfessorPlum, new BitmapImage(new System.Uri("/CluelessGame;component/Images/Professor Plum.png", UriKind.RelativeOrAbsolute)));

            Image image = new Image { Source = characterImageMap[gameObjects.ColonelMustard], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.ColonelMustard, image);
            image = new Image { Source = characterImageMap[gameObjects.MissScarlet], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.MissScarlet, image);
            image = new Image { Source = characterImageMap[gameObjects.MrGreen], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.MrGreen, image);
            image = new Image { Source = characterImageMap[gameObjects.MsPeakcock], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.MsPeakcock, image);
            image = new Image { Source = characterImageMap[gameObjects.MsWhite], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.MsWhite, image);
            image = new Image { Source = characterImageMap[gameObjects.ProfessorPlum], Width = 50, Height = 80 };
            UpdateIcon(gameObjects, gameObjects.ProfessorPlum, image);
        }

        private void UpdateIcon(GameObjects gameObjects, ObjectWithLocation objectWithLocation, Image image)
        {
            if (objectWithLocation.CurrentLocation == gameObjects.Ballroom)
            {
                CurrentGameBoard.Ballroom.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Billiardroom)
            {
                CurrentGameBoard.Billiardroom.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Conservatory)
            {
                CurrentGameBoard.Conservatory.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Diningroom)
            {
                CurrentGameBoard.Diningroom.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Hall)
            {
                CurrentGameBoard.Hall.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Library)
            {
                CurrentGameBoard.Library.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Lounge)
            {
                CurrentGameBoard.Lounge.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Study)
            {
                CurrentGameBoard.Study.Children.Add(image);
            }
            if (objectWithLocation.CurrentLocation == gameObjects.Kitchen)
            {
                CurrentGameBoard.Kitchen.Children.Add(image);
            }

            if (gameObjects.Study.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Hall.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayStudHall.Children.Add(image);
            }
            if (gameObjects.Hall.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Lounge.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayHallLounge.Children.Add(image);
            }
            if (gameObjects.Study.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Library.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayStudyLibrary.Children.Add(image);
            }
            if (gameObjects.Hall.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Billiardroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayHallBilliardroom.Children.Add(image);
            }
            if (gameObjects.Lounge.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Diningroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayLoungeDiningroom.Children.Add(image);
            }
            if (gameObjects.Library.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Conservatory.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayLibraryConservatory.Children.Add(image);
            }
            if (gameObjects.Billiardroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Diningroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayBilliardroomDiningroom.Children.Add(image);
            }
            if (gameObjects.Billiardroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Library.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayLibraryBilliardroom.Children.Add(image);
            }
            if (gameObjects.Billiardroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Ballroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayBilliardroomBallroom.Children.Add(image);
            }
            if (gameObjects.Diningroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Kitchen.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayDiningroomKitchen.Children.Add(image);
            }
            if (gameObjects.Conservatory.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Ballroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayConservatorBallroom.Children.Add(image);
            }
            if (gameObjects.Ballroom.AdjacentHallways.Contains(objectWithLocation.CurrentLocation)
                && gameObjects.Kitchen.AdjacentHallways.Contains(objectWithLocation.CurrentLocation))
            {
                CurrentGameBoard.HallwayBallroomKitchen.Children.Add(image);
            }
        }



        private void UpdateCards(List<Card> hand)
        {
            handImageMap = new Dictionary<BitmapImage, Card>();

            foreach (Card card in hand)
            {
                BitmapImage image = GetBitmapImageFromCard(card);

                if (CurrentGameManager.Disproving)
                {
                    if (card == CurrentGameManager.LastSuggestion.Character
                        || card == CurrentGameManager.LastSuggestion.Weapon
                        || card == CurrentGameManager.LastSuggestion.Room)
                    {
                        if (image != null)
                        {
                            handImageMap.Add(image, card);
                        }
                    }
                }
                else
                {
                    if (image != null)
                    {
                        handImageMap.Add(image, card);
                    }
                }
            }

            NotifyPropertyChanged("CardsInHand");
        }

        private BitmapImage GetBitmapImageFromCard(Card card)
        {
            BitmapImage image = null;
            if (card == GameManager.CurrentGameObjects.Ballroom.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/ballroom.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Billiardroom.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/billiardroom.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Candlestick.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/CandleStick.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.ColonelMustard.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/ColonelMustard.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Conservatory.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/conservatory.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Diningroom.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/diningroom.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Hall.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/hall.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Kitchen.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/kitchen.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Knife.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/Knife.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Library.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/library.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Lounge.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/lounge.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.MissScarlet.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/MissScarlet.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.MrGreen.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/MrGreen.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.MsPeakcock.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/MsPeacock.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.MsWhite.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/MsWhite.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Pipe.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/pipe.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.ProfessorPlum.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/Professor Plum.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Revolver.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/Revolver.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Rope.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/Rope.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Study.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/Study.png", UriKind.RelativeOrAbsolute));
            }
            else if (card == GameManager.CurrentGameObjects.Wrench.AssociatedCard)
            {
                image = new BitmapImage(new System.Uri("/CluelessGame;component/Images/Wrench.png", UriKind.RelativeOrAbsolute));
            }
            return image;
        }


        private void Window_Closed_1(object sender, EventArgs e)
        {
            App.NIU.Disconnect();

            noteBookScreen.ForceClose();
            characterSelectionScreen.ForceClose();

            App.ErrorLog.Terminate();
        }

        private void OnLogError(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(delegate()
            {
                chatTextBox.AppendText(message + "\n");
                chatTextBox.ScrollToEnd();
            }
            ));
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            App.ErrorLog.Initialize("Error Log.txt");
            CurrentGameManager = new GameManager(Dispatcher);
            CurrentGameBoard.CurrentGameManager = CurrentGameManager;
            //set up the DealtNewCards event callback
            CurrentGameManager.GameObjectsChanged += new GameManager.GameObjectsChangedHandler(OnGameObjectsChanged);
            CurrentGameManager.PlayerTurnChanged += new GameManager.PlayerTurnChangedHandler(OnPlayerTurnChanged);
            OnGameObjectsChanged(GameManager.CurrentGameObjects);
            App.ErrorLog.ExternalLogError += new ErrorLog.LogErrorDelegate(OnLogError);

            App.NIU.RegisterNetworkMessageHandler((Int32)NIUMessageIDs.CHAT_MESSAGE, HandleChatMessageNetworkMessage, Dispatcher.BeginInvoke);
            App.NIU.RegisterNetworkMessageHandler((Int32)NIUMessageIDs.START_GAME, HandleStartGameNetworkMessage, Dispatcher.BeginInvoke);
            App.NIU.RegisterNetworkMessageHandler((Int32)NIUMessageIDs.BEGIN_SELECT_CHARACTERS, HandleBeginSelectCharactersNetworkMessage, Dispatcher.BeginInvoke);
            App.NIU.RegisterNetworkMessageHandler((Int32)NIUMessageIDs.DISPROVE_SUGGESTION, HandleDisproveSuggestionNetworkMessage, Dispatcher.BeginInvoke);
        }

        private void OnPlayerTurnChanged(int PlayerTurn)
        {
            playersListBox.SelectedIndex = PlayerTurn;
        }

        private void buttonEndTurn_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentGameManager.IsLocalPlayerTurn)
            {
                if (CurrentGameManager.Suggesting)
                {
                    MessageBox.Show("You must wait until your suggestion is resolved");
                }
                else
                {
                    CurrentGameManager.EndTurn();
                }
            }
        }

        private void playersListBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void playersListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            playersListBox.SelectedIndex = CurrentGameManager.PlayerTurn;
        }

        private void disconnectClick(object sender, RoutedEventArgs e)
        {
            App.NIU.Disconnect();

            GameManager.CurrentGameObjects.ActivePlayerCount = 1;

            NotifyPropertyChanged("HostNewGameEnabled");
            NotifyPropertyChanged("JoinNewGameEnabled");
            NotifyPropertyChanged("DisconnectEnabled");
            NotifyPropertyChanged("StartGameEnabled");
        }

        private void gameRulesClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Process.Start("Rules.pdf");
            }
            catch (Exception exception)
            {
                MessageBox.Show("Could not launch Rules.pdf. Verify document exists");
            }
        }

        private void aboutClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Clue-Less version 1.0");
        }
    }
}
